package com.study.zzedu.ui.exercise.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.study.zzedu.R;
import com.study.zzedu.ui.exercise.adapter.OptionsListAdapter;
import com.study.zzedu.ui.exercise.bean.QuestionBean;
import com.study.zzedu.ui.exercise.view.NoScrollListview;
import com.study.zzedu.utils.AppConstant;
import com.study.zzedu.utils.Base64Utils;
import com.study.zzedu.utils.LogUtil;
import com.study.zzedu.utils.OkHttpUtils;
import com.study.zzedu.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import static com.study.zzedu.utils.AppConstant.chapterCode;

/**
 * @version 1.0
 * @author hzc
 * @date 2015-6-24
 */

public class QuestionItemActivity extends Activity {


	String myURL = "file:///android_asset/index.html#/index/testsub";
	//String myURL2 = "http://192.168.31.30:3001/#/index/mistakes";
	private static final String HTTP = "http://";
	private static final String HTTPS = "https://";
	private WebView mWebView;
	LocalBroadcastManager mLocalBroadcastManager;
	private RelativeLayout btn_back;

	public QuestionItemActivity() {
	}
//	public QuestionItemActivity(int index){
//		this.index = index;
//		questionBean = ExerciseActivity.questionlist.get(index);
//	}

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pager_item1);
		mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
		mWebView = findViewById(R.id.webView1);
		btn_back = findViewById(R.id.rl_back);
		btn_back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				finish();
			}
		});
		initWeb();
		initData();
	}

	private void initData() {
		OkHttpUtils.getInstance(this).getJsonForString(OkHttpUtils.BASE_URL + "/appCourseSubject/queryChaptersTest",
				new String[]{"chapterCode"}, new String[]{chapterCode}, new OkHttpUtils.HttpCallBack() {
					@Override
					public void onSuccess(String obj) {
						try {
							JSONObject jObject = new JSONObject(obj);
							if (0 == jObject.getInt("code")) {
								LogUtil.e("Forget", "在线测试-测试中——根据章节编号生成测试题成功");
								 JSONArray jArray = jObject.getJSONArray("data");
								 if(jArray.length()<1){
								 	ToastUtil.showShortToast("题目异常");
								 	return;
								 }
								 JSONObject job = jArray.getJSONObject(0);
								 AppConstant.testUUID = job.getString("testUUID");
								 JSONArray array2 = job.getJSONArray("list");
								final String jsString = "javascript:SET_TEST_DATA('"+Base64Utils.encode(array2.toString())+"')";

								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										new Handler().postDelayed(new Runnable() {
											@Override
											public void run() {
												mWebView.evaluateJavascript(jsString, new ValueCallback<String>() {
													@Override
													public void onReceiveValue(String s) {
														//将button显示的文字改成JS返回的字符串
														//buttonLeft.setText(s);
													}
												});
											}
										},1000);

									}
								});

							} else{
								finish();
								LogUtil.e("Forget", "在线测试-测试中——根据章节编号生成测试题失败");
								ToastUtil.showShortToast(""+jObject.get("message").toString());
								//resultListener.onError(jObject.get("message").toString());
							}
						} catch (Exception e) {
							e.toString();
						}
					}

					@Override
					public void onSuccess(JSONObject obj) {
						//resultListener.onSuccess(obj.toString());
					}

					@Override
					public void onError(String msg) {
						LogUtil.e("Forget", "在线测试-测试中——根据章节编号生成测试题失败");
						//resultListener.onError(msg);
					}
				});
	}

	private void initWeb() {
		mWebView.setWebViewClient(new MkWebViewClient());
		// 重写 WebChromeClient
		mWebView.setWebChromeClient(new MkWebChromeClient());

		WebSettings settings = mWebView.getSettings();
		// 启用 js 功能
		settings.setJavaScriptEnabled(true);
		mWebView.addJavascriptInterface(new AndroidGotData(), "AndroidGotData");
		// 设置浏览器 UserAgent
		settings.setUserAgentString(settings.getUserAgentString() + " mkBrowser/" + getVerName(this));

		// 将图片调整到适合 WebView 的大小
		settings.setUseWideViewPort(true);
		// 缩放至屏幕的大小
		settings.setLoadWithOverviewMode(true);

		// 支持缩放，默认为true。是下面那个的前提。
		settings.setSupportZoom(true);
		// 设置内置的缩放控件。若为false，则该 WebView 不可缩放
		settings.setBuiltInZoomControls(true);
		// 隐藏原生的缩放控件
		settings.setDisplayZoomControls(false);

		// 缓存
		settings.setCacheMode(WebSettings.LOAD_DEFAULT);
		// 设置可以访问文件
		settings.setAllowFileAccess(true);
		// 支持通过JS打开新窗口
		settings.setJavaScriptCanOpenWindowsAutomatically(true);
		// 支持自动加载图片
		settings.setLoadsImagesAutomatically(true);
		// 设置默认编码格式
		settings.setDefaultTextEncodingName("utf-8");
		// 本地存储
		settings.setDomStorageEnabled(true);
		settings.setPluginState(WebSettings.PluginState.ON);

		// 资源混合模式
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
		}

		try {
			if (Build.VERSION.SDK_INT >= 16) {
				Class<?> clazz = mWebView.getSettings().getClass();
				Method method = clazz.getMethod(
						"setAllowUniversalAccessFromFileURLs", boolean.class);//利用反射机制去修改设置对象
				if (method != null) {
					method.invoke(mWebView.getSettings(), true);//修改设置
				}
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		// 加载首页
		mWebView.loadUrl(myURL);
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	/**
	 * 获取版本号名称
	 *
	 * @param context 上下文
	 * @return 当前版本名称
	 */
	private static String getVerName(Context context) {
		String verName = "unKnow";
		try {
			verName = context.getPackageManager().
					getPackageInfo(context.getPackageName(), 0).versionName;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return verName;
	}

	/**
	 * 重写 WebViewClient
	 */
	private class MkWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// 设置在webView点击打开的新网页在当前界面显示,而不跳转到新的浏览器中

			if (url == null) {
				// 返回true自己处理，返回false不处理
				return true;
			}

			// 正常的内容，打开
			if (url.startsWith(HTTP) || url.startsWith(HTTPS)) {
				view.loadUrl(url);
				return true;
			}

			// 调用第三方应用，防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
			try {
				// TODO:弹窗提示用户，允许后再调用
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
				startActivity(intent);
				return true;
			} catch (Exception e) {
				return true;
			}
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			// 网页开始加载，显示进度条

		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
		}
	}


	/**
	 * 重写 WebChromeClient
	 */
	private class MkWebChromeClient extends WebChromeClient {
		private final static int WEB_PROGRESS_MAX = 100;

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			super.onProgressChanged(view, newProgress);

		}

		@Override
		public void onReceivedIcon(WebView view, Bitmap icon) {
			super.onReceivedIcon(view, icon);

		}

		@Override
		public void onReceivedTitle(WebView view, String title) {
			super.onReceivedTitle(view, title);

		}
	}

	// 继承自Object类
	public class AndroidGotData extends Object {

		// 定义JS需要调用的方法
		// 被JS调用的方法必须加入@JavascriptInterface注解
		@JavascriptInterface
		public void getData(String msg) {

			Intent intent = new Intent(QuestionItemActivity.this,ScantronItemActivity.class);
			intent.putExtra("answer",msg);
			startActivity(intent);
			finish();
			//ToastUtil.showLongToast(""+msg);
		}
	}
}